import React, { useEffect, useState, useRef } from 'react';
import './index.less';
import { View, Text, Image } from '@tarojs/components';
import TitleBar from '@/src/components/titleBar';
import Taro, { useRouter } from '@tarojs/taro';
import { AtTabs, AtTabsPane } from 'taro-ui';
import StoreInfo from '@/src/components/storeInfo';
import { SelfInfo } from '@/src/components/selfInfo';
import store from '@/src/store';
import { queryUserInfoFun } from '@/src/common/method/userInfoFun';
import CommentItem from '@/src/components/commentItem';
import ArticleItem from '@/src/components/articleItem';
import VedioItem from '@/src/components/vedioItem';
import BottomContainer from '@/src/components/bottomContainer';
import CommonBlank from '@/src/components/pageBlank';
import InfiniteScroll from '@/src/components/infiniteScroll';
import { publishUserListFun } from '@/src/common/method/homeFun';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';

let ucUserId = '';
let ucLoginPhone = '';

interface RouteParams {
  contentKind: string;
  contentType: string;
  userId: string;
  [key: string]: string | undefined;
}
//个人用户中心页面
const userCenter = () => {
  const pageSize = 10;
  const [current, setCurrent] = useState(0);
  const [loadingText, setLoadingText] = useState('');

  const { params } = useRouter<RouteParams>();
  const [userInfo, setUserInfo] = useState<any>([]);
  const [dataList, setDataList] = useState<any>([]); //列表
  const [maxPageNum, setMaxPageNum] = useState<number>(0);
  const [pageIndex, setPageIndex] = useState<any>(0);
  const [refresherTriggered, setRefresherTriggered] = useState(false);
  // 顶部
  const [scrollTop, setScrollTop] = useState(0);
  const tabList: any = [
    { title: '全部', value: 'ALL' },
    { title: '动态', value: 'DYNAMIC' },
    { title: '文章', value: 'ARTICLE' },
    { title: '视频', value: 'VIDEO' },
  ];
  // NEW: 绑定&解绑网络监听，防止监听器堆积造成CPU/内存升高
  useEffect(() => {
    const handler = getNetWorkStatus;
    Taro.onNetworkStatusChange(handler);
    return () => {
      try {
        Taro.offNetworkStatusChange(handler);
      } catch {}
    };
  }, []);

  useEffect(() => {
    ucUserId = String(Taro.getStorageSync('userId') ?? '').trim();
    ucLoginPhone = String(Taro.getStorageSync('mobile') ?? '').trim();
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('加载中...');
    //查询用户详情
    queryUserInfo();
    //获取我的发布
    getPublishContent('ALL');
  }, []);

  //获取我的发布
  const getPublishContent = (type: any, pageIndex: number = 1) => {
    const param = {
      ucUserId: params.userId,
      contentKind: params.contentKind,
      contentType: type,
      pageSize,
      pageNo: pageIndex,
    };
    return publishUserListFun(param)
      .then((res: any) => {
        setLoadingText('');
        if (res && res.totalCount > 0) {
          setMaxPageNum(Math.ceil(res.totalCount / pageSize));
          if (pageIndex === 1) {
            setDataList(res.list || []);
          } else {
            setDataList((prev: any) => (prev || []).concat(res.list || []));
          }
        } else if (pageIndex === 1) {
          setDataList([]);
          setMaxPageNum(0);
        }
      })
      .catch(() => setLoadingText(''));
  };

  //下拉查询数据
  const onEndReached = () => {
    if (loadingText === '加载中') {
      return false;
    }
    const index = pageIndex + 1;
    if (index > maxPageNum) {
      return false;
    }
    setPageIndex(index);
    setLoadingText('加载中...');
    return getPublishContent(tabList[current].value, index);
  };

  //加载下一页
  const loadMore = () => {
    let val: any = false;
    if (loadingText === '' && onEndReached) {
      setLoadingText('加载中...');
      val = onEndReached();
    }
  };

  //查询用户详情
  const queryUserInfo = () => {
    const param = {
      ucUserId: params.userId,
    };
    queryUserInfoFun(param).then((res: any) => {
      console.log(res, '查询用户详情');
      setUserInfo(res);
    });
  };

  //切换tab
  const handleClick = (index: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('加载中...');
    setCurrent(index);
    setDataList([]);
    setPageIndex(1);
    // 回到顶部（内层 ScrollView）
    setScrollTop(1);
    Taro.nextTick(() => setScrollTop(0));
    getPublishContent(tabList[index].value);
  };

  //跳转到文章详情
  const gotoDetail = (item: any, name: string) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (name === 'comment') {
      Taro.navigateTo({
        url: `/subPagesAccount/commentDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
      });
    } else if (name === 'article') {
      Taro.navigateTo({
        url: `/subPagesAccount/articleDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
      });
    } else {
      //跳转到视频详情
      Taro.navigateTo({
        url: `/subPagesAccount/vedioDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&from=mine&&contentType=${item.contentType}`,
      });
    }
  };

  const contentList = () => {
    return (
      <View>
        {dataList &&
          dataList.map((item: any, index: any) => {
            // FIX: key 更稳，用 contentId；避免频繁重排造成不必要的重建
            const key = item?.contentId
              ? `${item.contentType}-${item.contentId}`
              : `${item.contentType}-${index}`;
            return (
              <View key={key}>
                {item.contentType === 'DYNAMIC' &&
                  (current === 0 || current === 1) && (
                    <CommentItem
                      mine={true}
                      data={item}
                      home={true}
                      gotoDetail={(item: any, name: any) =>
                        gotoDetail(item, name)
                      }
                    />
                  )}
                {item.contentType === 'ARTICLE' &&
                  (current === 0 || current === 2) && (
                    <ArticleItem
                      mine={true}
                      data={item}
                      home={true}
                      gotoDetail={(item: any, name: any) =>
                        gotoDetail(item, name)
                      }
                    />
                  )}
                {item.contentType === 'VIDEO' &&
                  (current === 0 || current === 3) && (
                    <VedioItem
                      mine={true}
                      data={item}
                      home={true}
                      gotoDetail={(item: any, name: any) =>
                        gotoDetail(item, name)
                      }
                    />
                  )}
              </View>
            );
          })}
        {dataList.length === 0 && loadingText === '' && (
          <CommonBlank desc="暂无内容" visible={true} />
        )}
      </View>
    );
  };

  // 一级下拉刷新处理
  const handleRefreshFun = async () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (refresherTriggered) return; // 避免重入
    try {
      setRefresherTriggered(true);
      setLoadingText('加载中...');
      // 刷新永远从第一页拉取
      setPageIndex(1);
      await getPublishContent(tabList[current].value, 1);
    } finally {
      setRefresherTriggered(false); // 结束刷新
      setLoadingText('');
    }
  };

  const { windowHeight, screenWidth } = Taro.getSystemInfoSync();
  const rpx2px = (rpx: number) => (rpx / 750) * screenWidth;
  const contentPx =
    windowHeight - rpx2px(store.commonStore.pageAreaTop) - rpx2px(290);

  return (
    <View
      className="user-center-container"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={true} title=""></TitleBar>

      {/* 个人信息 */}
      <SelfInfo
        title={userInfo.ucNickname}
        account={userInfo.ucUserId}
        userTagBrandInfoVo={userInfo.userTagBrandInfoVo}
        brand="哈瓦那雪茄吧"
        portrait={userInfo.ucAvatarUrl}
        ip={userInfo.address}
        onExit={() => console.log('')}
      />

      {/* 认证商家 */}
      {userInfo.userTagStoreInfoVo && (
        <StoreInfo
          isHome={true}
          storeInfo={userInfo.userTagStoreInfoVo}
          style={{ background: '#fff' }}
        />
      )}

      {/* 认证品牌用图片已沟通睿麟 */}
      {userInfo && userInfo.userTagBrandInfoVo && (
        <View className="user-center-certify-brand">
          <Image
            src={userInfo.userTagBrandInfoVo.brandImage}
            className="brand-logo"
            lazyLoad // NEW: 懒加载图片，降低离屏成本
          />
        </View>
      )}

      {/* tab内容展示  */}
      <View
        className="user-center-content"
        style={{
          height: `calc(100vh - ${store.commonStore.pageAreaTop}rpx - 290rpx)`,
        }}
      >
        <AtTabs
          current={current}
          tabList={tabList}
          className="home-tab"
          onClick={(index) => handleClick(index)}
        >
          <AtTabsPane current={current} index={0}>
            <View style={{ height: `${contentPx}px` }}>
              <InfiniteScroll
                hasMore={pageIndex < maxPageNum}
                style={{ height: '100%' }}
                scrollTop={scrollTop}
                loadMore={() => loadMore()}
                dataList={dataList}
                refresherTriggered={refresherTriggered}
                handleRefresh={() => handleRefreshFun()}
                loading={loadingText === '' ? false : true}
                content={contentList()}
              />
            </View>
            <BottomContainer />
          </AtTabsPane>

          <AtTabsPane current={current} index={1}>
            <View style={{ height: `${contentPx}px` }}>
              <InfiniteScroll
                style={{ height: '100%' }}
                scrollTop={scrollTop}
                hasMore={pageIndex < maxPageNum}
                loadMore={() => loadMore()}
                refresherTriggered={refresherTriggered}
                handleRefresh={() => handleRefreshFun()}
                dataList={dataList}
                loading={loadingText === '' ? false : true}
                content={contentList()}
              />
            </View>
            <BottomContainer />
          </AtTabsPane>

          <AtTabsPane current={current} index={2}>
            <View style={{ height: `${contentPx}px` }}>
              <InfiniteScroll
                hasMore={pageIndex < maxPageNum}
                style={{ height: '100%' }}
                scrollTop={scrollTop}
                loadMore={() => loadMore()}
                refresherTriggered={refresherTriggered}
                handleRefresh={() => handleRefreshFun()}
                dataList={dataList}
                loading={loadingText === '' ? false : true}
                content={contentList()}
              />
            </View>
            <BottomContainer />
          </AtTabsPane>

          <AtTabsPane current={current} index={3}>
            <View style={{ height: `${contentPx}px` }}>
              <InfiniteScroll
                style={{ height: '100%' }}
                scrollTop={scrollTop}
                hasMore={pageIndex < maxPageNum}
                refresherTriggered={refresherTriggered}
                handleRefresh={() => handleRefreshFun()}
                loadMore={() => loadMore()}
                dataList={dataList}
                loading={loadingText === '' ? false : true}
                content={contentList()}
              />
            </View>
            <BottomContainer />
          </AtTabsPane>
        </AtTabs>
      </View>
    </View>
  );
};
export default userCenter;
